#include <iostream>
using namespace std;
int result[101];
int result_num=0;
int main()
{
	int m,n;
	int t;
	while(cin>>t){
		for(int i=0;i<t;i++){
			cin>>m>>n;
			long long sum=0;
			while(1){
				sum=sum+m/n;
				m=m/n;
				if(m==0) break;
			}
			result[result_num]=sum;
			result_num++;
		}
		for(int j=0;j<t;j++){
			cout<<result[j]<<endl;
		}
		result_num=0;
	}
}
